package com.fyl.custom_spring.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 存储和管理多个PropertyValue对象
 */
public class MutablePropertyValues implements Iterable<PropertyValue> {
    //定义list
    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
        this.propertyValueList = new ArrayList<PropertyValue>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        if(null==propertyValueList){
            this.propertyValueList=new ArrayList<>();
        }else {
        this.propertyValueList = propertyValueList;
        }
    }
    //获取所有的propertyValue对象
    public PropertyValue[] getPropertyValues(){
        return propertyValueList.toArray(new PropertyValue[0]);
    }

    //根据name属性获取propertyValue对象
    public PropertyValue getPropertyValue(String propertyName){
        for (PropertyValue propertyValue : propertyValueList) {
            if(propertyValue.getName().equals(propertyName)){
                return propertyValue;
            }
        }
        return null;
    }

    //判断集合是否为空
    public boolean isEmpty(){
        return propertyValueList.isEmpty();
    }

    //添加propertyValue对象
    public MutablePropertyValues addPropertyValue(PropertyValue propertyValue){
        //集合中如果有重复的name属性，则进行覆盖
        for (int i = 0; i < propertyValueList.size(); i++) {
            PropertyValue currentPv = propertyValueList.get(i);
            if(currentPv.getName().equals(propertyValue.getName())){
                propertyValueList.set(i, propertyValue);
                return this;
            }
        }
        propertyValueList.add(propertyValue);
        return this;
    }

    //判断list中是否有指定name属性的对象
    public boolean contains(String propertyName){
        return getPropertyValue(propertyName)!=null;
    }

    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }
}
